# utils/config_util.py
import yaml
import os


class ConfigUtil:
    @staticmethod
    def load_test_params(yaml_file):
        """加载测试参数YAML文件"""
        params_path = os.path.join(
            os.path.dirname(os.path.dirname(__file__)),
            "config", "test_params", yaml_file
        )
        if not os.path.exists(params_path):
            raise FileNotFoundError(f"测试参数文件不存在：{params_path}")
        with open(params_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)["test_cases"]  # 返回测试用例列表

    @staticmethod
    def _load_config():
        """加载配置文件（私有方法，内部调用）"""
        # 拼接配置文件路径（兼容不同操作系统）
        config_path = os.path.join(
            os.path.dirname(os.path.dirname(__file__)),  # 项目根目录（longguoWebUI）
            "config", "environments", "config.yaml"
        )
        if not os.path.exists(config_path):
            raise FileNotFoundError(f"配置文件不存在：{config_path}")
        with open(config_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)

    # 浏览器配置
    @staticmethod
    def get_browser():
        return ConfigUtil._load_config().get("browser", "chrome").lower()

    # 邮件配置
    @staticmethod
    def get_email_config():
        return ConfigUtil._load_config().get("email", {})

    # 测试URL
    @staticmethod
    def get_test_url():
        return ConfigUtil._load_config().get("test_url")

    # 数据库配置
    @staticmethod
    def get_db_config():
        return ConfigUtil._load_config().get("db", {})

    # 测试账号（新增）
    @staticmethod
    def get_valid_username():
        return ConfigUtil._load_config().get("test_account", {}).get("valid_username")

    @staticmethod
    def get_valid_password():
        return ConfigUtil._load_config().get("test_account", {}).get("valid_password")

    @staticmethod
    def get_invalid_password():
        return ConfigUtil._load_config().get("test_account", {}).get("invalid_password")

    # 新增：加载页面元素配置
    @staticmethod
    def load_page_locators(page_name):
        """加载页面元素配置"""
        locator_path = os.path.join(
            os.path.dirname(os.path.dirname(__file__)),  # 项目根目录
            "config", "pages", f"{page_name}.yaml"
        )
        if not os.path.exists(locator_path):
            raise FileNotFoundError(f"页面元素配置不存在：{locator_path}")
        with open(locator_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
